import clr 
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')
from System.Windows.Forms import *
from System.Drawing import *
#from System.Drawing import Bitmap
from System.Drawing.Imaging import ImageFormat
from System.Windows.Forms import DialogResult, SaveFileDialog
from math import *
from LoadLib import *
from ChrisExamples import *
from ParkerExamples import *
from boots import *
from Emily import*
from kaeli import*
import random

z.size = 100
z.time = 0.0
z.image = []
z.Bitmap = Bitmap(1,1)
z.frame = 0
z.animating = False
z.a = 1
z.frames = 10
statusLabel = Label()
frameBox = TextBox()
sizeBox = TextBox()
timeBox = TextBox()
aaBox = TextBox()
stopAnimation = Button()

#def f(p):
 #   if p.x < z.time:
  #      return C(1,0,0)
   # return C(0,1,0)

def from8(x):		
    x = x/255.0
    if x < 0:
        return 0		
    if x > 1:
        return 1		
    return x

def fromColor(self):		
	    return C(from8(self.R), from8(self.G), from8(self.B), from8(self.A))

# Various 1-D functions that yield fractions:


# Functions that work at all dimensions:
disk = step |o| (one |fminus| norm)

z.image1 = lambda p: C(0,0,0,0)
z.image2 = lambda p: C(0,0,0,0)
z.image3 = lambda p: C(0,0,0,0)
z.iBitmap1 = Bitmap(1,1)
z.iBitmap2 = Bitmap(1,1)
z.iBitmap3 = Bitmap(1,1)
z.thumb1 = None
z.thumb2 = None
z.thumb3 = None
z.f = lambda p: C(1,1,1,1)

def displayAll(obj, e): 
    g = e.Graphics
    g.DrawImage(z.Bitmap, Point(0,0))

def getThumbNail(f, size):
    px = lambda x:((2.0*x)/(size-1))-1
    b = Bitmap(size, size)
    for r in range(size):
        for c in range(size):
            color = f(P2(px(r), px(c)))
            if isinstance(color, C):
             b.SetPixel(r,c,color.toColor())
            else:
             print"Image not returning a color: " + str(color)
    return b

def refreshBitmap(f,a = 1):
    aa = []
    px = lambda x:((2.0*x)/(z.size-1))-1
    b = Bitmap(z.size, z.size)
    statusLabel.Text = "Thinking"
    print "this is z.a"
    print z.a
    
    if z.a <= 1:
     for r in range(z.size):
        for c in range(z.size):
            color = f(P2(px(r), px(c)))
            b.SetPixel(r,c,color.toColor())
     z.Bitmap = b
     z.image.Add(z.Bitmap)
     print "not aa"
     print len(z.image)-1
    else:
     for n in range(a):
         dr = random.random()-.5
         dc = random.random()-.5
         p = 0
         for r in range(z.size):
            for c in range(z.size):
                color = f(P2(px(r+dr), px(c+dc)))
                
                #print "anti-aliasing"
                if n == 0: 
                    aa.Add(color)
                else:
                    aa[p] = aa[p]+color
                    p = p + 1 
                   #b.SetPixel(r,c,color.toColor())
     p = 0
     for r in range(z.size):
        for c in range(z.size):
            b.SetPixel(r,c,(aa[p]/a).toColor())
            p = p+1
     z.Bitmap = b
     z.image.Add(z.Bitmap)
     statusLabel.Text = "Done"
     print "aa"
     print len(z.image)-1
def toInt(s):
    try:
        return int(s)
    except:
        return "Error"



def toFloat(s):
    try:
      return float(s)
    except:
        return "Error"

def Refresh(obj,e):
    z.size = toInt(sizeBox.Text)
    z.time = toFloat(timeBox.Text)
    z.a = toInt(aaBox.Text)
    z.image = []
    refreshFunction()
    refreshBitmap(z.f,z.a)
    z.image.Add(z.Bitmap)
    z.pb.Invalidate()


    #p = functionBox.Text  
def refreshFunction():
    try:
        z.f = eval(z.functionBox.Text)
        print z.size
        print z.time
    except:
        print "exception" 
        refreshBitmap(lambda p: black)
        z.pb.Invalidate()
        return #need to display error message
def Animate(obj,e):
 #add image/save
    #refersh/incriment
    z.size = toInt(sizeBox.Text)
    z.a = toInt(aaBox.Text)
    z.image = []
    z.frames = toInt(frameBox.Text)
    statusLabel.Text = "Thinking"
    z.pb.Invalidate()
    refreshFunction()
    for r in range(0,z.frames + 1,1):
         refreshBitmap(z.f,z.a)
         z.time = z.time + .1
         
         z.pb.Invalidate()
         z.frame = len(z.image)-1
    statusLabel.Text = "Done"
   
def Next(obj,e):
    print "Next"
    print z.frame
    if z.frame <= len(z.image)-1:
     z.Bitmap = z.image[z.frame]
     z.frame = z.frame + 1
     z.pb.Invalidate()
    else:
        z.frame = 0
    
def Previous(obj,e):
    print "Previous"
    print z.frame
    if z.frame >= 0:
     z.Bitmap = z.image[z.frame]
     z.frame = z.frame -1
     z.pb.Invalidate()
    else:
        z.frame = len(z.image)-1
#test = "C:\\ Documents and Settings \\ stu755097 \\ Desktop \\ Test1.JPG"
def playAnimation(obj,e):
    print "Play Animation"
    z.frame = 0
    z.animating = True
    stopAnimation.Visible = True
    #while(playing):
def stopAnimating(obj,e):
    print "animation is stopping"
    z.animating = False
    stopAnimation.Visible = False       


def FromFile(file):
    pic = Image.FromFile(file)
    image = Bitmap(pic)
    s = max(pic.Height, pic.Width)
    p = (abs(pic.Width -pic.Height)) / 2
    if (pic.Width > pic.Height): ip = 0 
    else: ip = p
    if(pic.Height > pic.Width): jp = 0
    else: jp = p

    def f(p):
        i = int((p.x + 1) / 2.0 * s) - ip
        j = int((p.y + 1) / 2.0 * s) - jp
        if(i >= 0 and i < pic.Width and j >= 0 and j < pic.Height):

            #print("j: " + str(j))
            #print("i: " + str(i))
            #print("s: " + str(s))
            #print("width: " + str(pic.Width))
            #print("height: " + str(pic.Height))
            return fromColor(image.GetPixel(i, j))
        return C(0,0,0,0)
    return f

#f = FromFile(test)

def saveImage(obj,e):
    n = 0
    dialog = SaveFileDialog()
    dialog.Title = 'Save Chart as Jpg Image'
    dialog.Filter = 'Image Files(*.JPG;*.GIF)|*.JPG;*.GIF|All files (*.*)|*.*'
    dialog.FileName = "TesterImage0"
    
    for n in range(0,len(z.image)-1):
     if dialog.ShowDialog() == DialogResult.OK:
            #     Should really check what format they *really* want!
            try:
           
             z.image[n].Save(dialog.FileName, ImageFormat.Jpeg)

            except IOError, e:
                print 'An error occurred:', e


def loadImage():
    dialog = OpenFileDialog()
    dialog.Title = 'Open Image'
    dialog.Filter = 'Image Files(*.JPG;*.GIF)|*.JPG;*.GIF|All files (*.*)|*.*'

    if dialog.ShowDialog() == DialogResult.OK:
            #     Should really check what format they *really* want!
            try:
               return FromFile(dialog.FileName)

            except IOError, e:
                print 'An error occurred:', e
                return None 
    return None

def loadImage1(obj, e):
    i =loadImage()
    if i != None:
        z.image1 = i
        z.thumb1 = getThumbNail(i, 100)
        z.tb1.Invalidate()
        
def displayThumb1(obj, e):
    if z.thumb1 != None:
        g = e.Graphics
        g.DrawImage(z.thumb1, Point(0,0))

def loadImage2(obj, e):
    i =loadImage()
    if i != None:
        z.image2 = i
        z.thumb2 = getThumbNail(i, 100)
        z.tb2.Invalidate()
        
def displayThumb2(obj, e):
    if z.thumb2 != None:
        g = e.Graphics
        g.DrawImage(z.thumb2, Point(0,0))

def loadImage3(obj, e):
    i =loadImage()
    if i != None:
        z.image3 = i
        z.thumb3 = getThumbNail(i, 100)
        z.tb3.Invalidate()
        
def displayThumb3(obj, e):
    if z.thumb3 != None:
        g = e.Graphics
        g.DrawImage(z.thumb3, Point(0,0))
def tick(obj,e):
    if z.animating:
        Next(obj,e)
class MyForm(Form):
  
    def __init__(self):
       
         #timer
         timer = Timer()
         timer.Interval = 200
         timer.Enabled  = True
         timer.Tick += tick
         #anit-aliasing Textbox
         aaBox.Text = "1"
         aaBox.Location = Point(775,40)
         aaText = Label()
         aaText.Text = "Anti-Aliasing:"
         aaText.Location = Point(775,10)
         self.Controls.Add(aaText)
         self.Controls.Add(aaBox)
         #framebox
         frameBox.Text = "10"
         frameBox.Location = Point(775,110)
         frameText = Label()
         frameText.Text = "Number of Frames:"
         frameText.Location = Point(775,80)
         self.Controls.Add(frameBox)
         self.Controls.Add(frameText)
         #Thumb1 Load Button
         loadButton1 = Button()
         loadButton1.Text = "Load"
         loadButton1.Location =Point(675,160)
         self.Controls.Add(loadButton1)
         loadButton1.Click += loadImage1
          #Thumb2 Load Button
         loadButton2 = Button()
         loadButton2.Text = "Load"
         loadButton2.Location =Point(675,300)
         self.Controls.Add(loadButton2)
         loadButton2.Click += loadImage2
          #Thumb3 Load Button
         loadButton3 = Button()
         loadButton3.Text = "Load"
         loadButton3.Location =Point(675,440)
         self.Controls.Add(loadButton3)
         loadButton3.Click += loadImage3
         #Save Button 
         saveButton = Button()
         saveButton.Text = "Save Button"
         saveButton.Location =Point(675,600)
         self.Controls.Add(saveButton)
         saveButton.Click += saveImage
         #SizeControls
         sizeBox.Text = "100"
         sizeBox.Location = Point(675,40)
         sizeText = Label()
         sizeText.Text = "Size:"
         sizeText.Location = Point(675,10)
         self.Controls.Add(sizeText)
         self.Controls.Add(sizeBox)
         #timeControls
         
         statusLabel.Text
         statusLabel.Location = Point(20,575)
         self.Controls.Add(statusLabel)
         timeBox.Text = "0.0"
         timeBox.Location = Point(675,110)
         timeText = Label()
         timeText.Text = "Time: "
         timeText.Location = Point(675,80)
         self.Controls.Add(timeText)
         self.Controls.Add(timeBox)
         #refresh Button
         refreshButton = Button()
         refreshButton.Text = "Refresh"
         refreshButton.Location = Point(575,600)
         self.Controls.Add(refreshButton)
         refreshButton.Click += Refresh
         #function Box
         functionBox = TextBox()
         functionBox.Text = "lambda p: C(1,1,1) if abs(p) > .5 else C(0,0,0)"
         functionBox.Location = Point(20,600)
         functionBox.Width = 400
         functionText = Label()
         functionText.Text = "Function Box:"
         z.functionBox = functionBox
         functionText.Location = Point(20,575)
         self.Controls.Add(functionText)
         self.Controls.Add(functionBox)
         #animate button
         animateButton = Button()
         animateButton.Location = Point(475,600)
         animateButton.Text = "Animate"
         self.Controls.Add(animateButton)
         animateButton.Click += Animate
         #nextButton
         nextButton = Button()
         nextButton.Location = Point(200,700)
         nextButton.Text = "next"
         self.Controls.Add(nextButton)
         nextButton.Click += Next
         #previousButton
         prevButton = Button()
         prevButton.Location = Point(100,700)
         prevButton.Text = "Previous"
         self.Controls.Add(prevButton)
         prevButton.Click += Previous
         #playAnimation
         pAnimation = Button()
         pAnimation.Text = "Play Animation"
         pAnimation.Location = Point(575,700)
         self.Controls.Add(pAnimation)
         pAnimation.Click += playAnimation

         #stopAnimation
         
         stopAnimation.Text = "Stop"
         stopAnimation.Location = Point(650,700)
         self.Controls.Add(stopAnimation)
         stopAnimation.Visible = False
         stopAnimation.Click += stopAnimating
         self.Width = 1000
         self.Height = 1000
         tb1 = PictureBox()
         tb1.Height = 100
         tb1.Width = 100
         tb1.Location = Point(675,190)
         tb1.Paint += displayThumb1
         self.Controls.Add(tb1)
         z.tb1 = tb1
         tb2 = PictureBox()
         tb2.Height = 100
         tb2.Width = 100
         tb2.Location = Point(675, 330)
         tb2.Paint += displayThumb2
         self.Controls.Add(tb2)
         z.tb2 = tb2
         tb3 = PictureBox()
         tb3.Height = 100
         tb3.Width = 100
         tb3.Location = Point(675, 470)
         tb3.Paint += displayThumb3
         self.Controls.Add(tb3)
         z.tb3 = tb3
         pb = PictureBox()
         pb.Height = 1000
         pb.Width = 1000
         pb.Location = Point(0,0)
         pb.Paint += displayAll
         self.Controls.Add(pb)
         #z.errorText = errorText
         print z.size
         print z.time
         z.pb = pb
         z.pb.Invalidate()

form = MyForm()
Application.Run(form)
